package org.jeecg.modules.demo.shopprojectcart.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.shopprojectcart.entity.ShopProjectCart;
import org.jeecg.modules.demo.shopprojectcart.service.IShopProjectCartService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 项目购物车
 * @Author: jeecg-boot
 * @Date: 2022-01-14
 * @Version: V1.0
 */
@Api(tags = "项目购物车")
@RestController
@RequestMapping("/shopprojectcart/ShopProjectCart")
@Slf4j
public class ShopProjectCartController extends JeecgController<ShopProjectCart, IShopProjectCartService> {
    @Autowired
    private IShopProjectCartService shopProjectCartService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "项目购物车-分页列表查询")
    @ApiOperation(value = "项目购物车-分页列表查询", notes = "项目购物车-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShopProjectCart shopProjectCart,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<ShopProjectCart> queryWrapper = new QueryWrapper<>();
        QueryGenerator.initQueryWrapper(queryWrapper, shopProjectCart, req.getParameterMap());
        List<ShopProjectCart> list = shopProjectCartService.list(queryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list1 = list.stream().map(spc -> {
            Map<String, Object> m = ToolsUtils.objectToMap(spc);
            ProjectManagement pm = projectManagementService.getById(spc.getProjectId());
            if (pm != null) {
                m.put("commodityName", pm.getProjectName());
                m.put("commoditySpec", pm.getItemDescription());
                m.put("commodityPic", pm.getProjectPic());
                m.put("price", pm.getProjectPrice());
            }
            Date createTime = (Date) m.get("createTime");
            Date updateTime = (Date) m.get("updateTime");
            if (createTime != null) {
                m.put("createTime", sdf.format(createTime));
            }
            if (updateTime != null) {
                m.put("updateTime", sdf.format(updateTime));
            }
            return m;
        }).collect(Collectors.toList());
        return Result.OK(list1);
    }

    /**
     * 查询购物车项目列表
     */
    @RequestMapping(value = "/getListByMemberId", method = RequestMethod.GET)
    public Result<List<Map<String, Object>>> getListByMemberId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "storeId", required = true) String storeId,
            @RequestParam(name = "memberId", required = true) String memberId) {
        Result<List<Map<String, Object>>> result = new Result<>();
        List<Map<String, Object>> list = shopProjectCartService.getListByMemberId(pageNo, 10, storeId, memberId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 添加
     *
     * @param shopProjectCart
     * @return
     */
    @AutoLog(value = "项目购物车-添加")
    @ApiOperation(value = "项目购物车-添加", notes = "项目购物车-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopProjectCart shopProjectCart, HttpServletRequest req) {

        ShopProjectCart one = shopProjectCartService.getOne(new QueryWrapper<ShopProjectCart>()
                .eq("member_id", shopProjectCart.getMemberId())
                .eq("project_id", shopProjectCart.getProjectId())
                .eq("store_id", shopProjectCart.getStoreId()));
        if (one != null) {
            // 有记录，数量增加
            one.setQty(one.getQty() + shopProjectCart.getQty());
            shopProjectCartService.updateById(one);
            return Result.OK("成功，数量+" + shopProjectCart.getQty() + "！");
        }
        // 无记录，新增
        shopProjectCartService.save(shopProjectCart);
        return Result.OK("添加成功！");
    }

    /**
     * 项目数量加1
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目数量加1")
    @ApiOperation(value = "项目数量加1", notes = "项目数量加1")
    @PutMapping(value = "/addQty")
    public Result<?> addQty(@RequestParam(name = "id", required = true) String id) {
        shopProjectCartService.addQty(id);
        return Result.OK("增加成功！");
    }

    /**
     * 项目数量减1
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目数量减1")
    @ApiOperation(value = "项目数量减1", notes = "项目数量减1")
    @PutMapping(value = "/reduceQty")
    public Result<?> reduceQty(@RequestParam(name = "id", required = true) String id) {
        ShopProjectCart one = shopProjectCartService.getById(id);
        if (one.getQty() <= 1) {
            // 数量小于等于1，减完剩0，直接删除记录
            shopProjectCartService.removeById(id);
            return Result.OK("减少成功！（记录已删除）");
        }
        // 数量大于1，执行-1操作
        shopProjectCartService.reduceQty(id);
        return Result.OK("减少成功！");
    }

    /**
     * 项目数量修改
     *
     * @return
     */
    @AutoLog(value = "项目数量修改")
    @ApiOperation(value = "项目数量修改", notes = "项目数量修改")
    @PutMapping(value = "/updateQty")
    public Result<?> updateQty(@RequestBody JSONObject json) {
        String id = json.getString("id");
        String qty = json.getString("qty");
        shopProjectCartService.updateQty(id, Integer.valueOf(qty));
        return Result.OK("修改成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目购物车-通过id删除")
    @ApiOperation(value = "项目购物车-通过id删除", notes = "项目购物车-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        shopProjectCartService.removeById(id);
        return Result.OK("删除成功！");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目购物车-批量删除")
    @ApiOperation(value = "项目购物车-批量删除", notes = "项目购物车-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shopProjectCartService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目购物车-通过id查询")
    @ApiOperation(value = "项目购物车-通过id查询", notes = "项目购物车-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShopProjectCart spc = shopProjectCartService.getById(id);
        if (spc == null) {
            return Result.error("未找到对应数据");
        }
        Map<String, Object> m = ToolsUtils.objectToMap(spc);
        ProjectManagement pm = projectManagementService.getById(spc.getProjectId());
        if (pm != null) {
            m.put("commodityName", pm.getProjectName());
            m.put("commoditySpec", pm.getItemDescription());
            m.put("commodityPic", pm.getProjectPic());
            m.put("price", pm.getProjectPrice());
        }
        return Result.OK(m);
    }

}
